
// ----- Para_Forum_MsgBody class ----------------------------------------
function  Para_Forum_MsgBody( id, html, expanded ) {
    this.id       = id;
    this.html     = html;
    this.expanded = expanded;
}


//------ ParaForum class --------------------------------------------------
function Para_Forum( ) {

    // properties
    this.console = $('para_forum_console');

    // mode can be INDEX, THREAD or EDITOR;
    this.mode          = "INDEX";

    // properties for index view
    this.index_html    = null;
    this.thread_count  = 0;

    // properties for thread view
    this.thread_html   = null;
    this.cur_thread_id = null;

    // properties for editor view
    // submode can be CREATE or REPLY (or null)
    this.editor_submode = null;
    this.form_html      = null;
    this.reply_msg_id   = null;
    this.teditor        = null;


    this.bodies = new Array();


    // methods
    this.rpc_response        = Para_Forum_RPC_Response;
    this.load_thread         = Para_Forum_Load_Thread;
    this.show_thread         = Para_Forum_Show_Thread;
    this.load_index          = Para_Forum_Load_Index;
    this.show_index          = Para_Forum_Show_Index;
    this.expand_body         = Para_Forum_Expand_Body;
    this.hide_body           = Para_Forum_Hide_Body;
    this.handle_events       = Para_Forum_Handle_Events;
    this.load_form           = Para_Forum_Load_Form;
    this.show_form           = Para_Forum_Show_Form;
    this.post_new_thread     = Para_Forum_Post_New_Thread;
    this.reply_to_msg        = Para_Forum_Reply_To_Msg;
    this.send_preview_req    = Para_Forum_Send_Preview_Req;
    this.show_preview        = Para_Forum_Show_Preview;
    this.hide_preview        = Para_Forum_Hide_Preview;

    // Server Events
    this.sev_get_index     = Para_Forum_SEV_GetIndex;
    this.sev_get_thread    = Para_Forum_SEV_GetThread;
    this.sev_get_body      = Para_Forum_SEV_GetBody;
    this.sev_form_load     = Para_Forum_SEV_FormLoad;
    this.sev_create_thread = Para_Forum_SEV_CreateThread; 
    this.sev_post_reply    = Para_Forum_SEV_PostReply; 
    this.sev_preview_msg   = Para_Forum_SEV_PreviewMsg; 

    //User Events
    this.uev_view_thread    = Para_Forum_UEV_ViewThread;
    this.uev_toggle_body    = Para_Forum_UEV_ToggleBody;
    this.uev_view_index     = Para_Forum_UEV_ViewIndex;
    this.uev_create_thread  = Para_Forum_UEV_CreateThread;
    this.uev_reply_to_msg   = Para_Forum_UEV_ReplyToMsg;
    this.uev_send_msg       = Para_Forum_UEV_SendMsg;
    this.uev_preview_msg    = Para_Forum_UEV_PreviewMessage;
    this.uev_tformat        = Para_Forum_UEV_TFormat;


    // Internal methods
    this._add_msgbody     = Para_Forum__Add_MsgBody;
    this._find_body_index = Para_Forum__Find_Body_Index;
    this._find_body       = Para_Forum__Find_Body;
}


function Para_Forum_RPC_Response( response ) {
    var postback = response.postback;

    switch (postback) {
    case "forum_get_index":
        this.sev_get_index( response ); break;
    case "forum_get_thread":
        this.sev_get_thread( response ); break;
    case "forum_get_body":
        this.sev_get_body( response ); break;
    case "forum_form_load":
        this.sev_form_load( response ); break;
    case "forum_create_thread":
        this.sev_create_thread( response ); break;
    case "forum_post_reply":
        this.sev_post_reply( response ); break;
    case "forum_preview_msg":
        this.sev_preview_msg( response ); break;
    default:
        alert( "Unknown postback:" + postback );
    }
}


function Para_Forum_Load_Thread( thread_id ) {
   var request = 
        {
            operation: "forum_get_thread",
            postback:  "forum_get_thread",
            param: {
                thread_id: thread_id,
                expanded_body_ids: null
            }
        };
    parapara.send_rpc( request );
    this.console.set('html', 'Loading Thread');

}


function Para_Forum_Load_Index() {
   var request = 
        {
            operation: "forum_get_threads",
            postback:  "forum_get_index",
            param: {
            }
        };
    parapara.send_rpc( request );

    this.console.set('html', 'Loading Index');
}


function Para_Forum_Show_Index( html ) {
    this.mode = 'INDEX';
    this.console.set( 'html', html );
}


function Para_Forum_Show_Thread( html, thread_id ) {
    this.cur_thread_id = thread_id;
    this.thread_html   = html;


    this.mode = 'THREAD';
    this.console.set( 'html', html );

    var thread_div = $('para_forum_thread_' + thread_id);
    if(!thread_div)
        alert("Buuuuuuuuuuuuuuuuuuhaa " + thread_id);

    this.bodies = new Array();

    //var fx = new Fx.Style(thread_div, 'background-color', {duration:1000});
    //FIXME: remove hard coded colors
    //fx.start('#000000', '#ffffff');

}


function Para_Forum_Expand_Body( html, msg_id) {
    var body_container = $('para_forum_msgbody_container_' + msg_id );

    if(!body_container)
        return;

    if(html != null) {
        this._add_msgbody(  msg_id, html, true );
    }
    else {
        var mb = this._find_body( msg_id );
        if(mb != null) {
            html = mb.html;
            mb.expanded = true;
        }
    }

    body_container.set( 'html', html );
    body_container.removeClass('para_hidden');
    body_container.addClass('para_shown');
}


function Para_Forum_Hide_Body( msg_id ) {
    var body_container = $('para_forum_msgbody_container_' + msg_id );

    if(!body_container)
        return;

    var mb = this._find_body( msg_id );
    if(mb) {
        mb.expanded = false;
    }

    body_container.empty();
    body_container.removeClass('para_shown');
    body_container.addClass('para_hidden');
}


function Para_Forum_Handle_Events( events ) {
    
}


function Para_Forum_Load_Form( ) {
   var request = 
        {
            operation: "get_bit",
            postback:  "forum_form_load",
            param: {
                bit: "forum_msg_form"
            }
        };
    parapara.send_rpc( request );
    this.console.set('html', 'Loading Form');
}


function Para_Forum_Show_Form( ) {
    this.console.set( 'html', this.form_html );
    var textarea = $('para_forum_input_teditor');
    if(!textarea) {
        alert("No text area found!");
    }
    this.teditor = new Para_TextEditor( textarea );
}


function Para_Forum_Post_New_Thread( subject, text, screen_name ) {
    var request = 
        {
            operation: "forum_create_thread",
            postback:  "forum_create_thread",
            param: {
                subject: subject,
                text:    text,
                screen_name: screen_name
            }
        };
    parapara.send_rpc( request );
}


function Para_Forum_Reply_To_Msg( subject, text, screen_name, reply_to ) {
       var request = {
           operation: "forum_post_reply",
           postback:  "forum_post_reply",
           param: {
               subject: subject,
               text:    text,
               screen_name: screen_name,
               reply_to: reply_to
           }
       };
    parapara.send_rpc( request );
}


function Para_Forum_Send_Preview_Req( subject, text, screen_name ) {
       var request = {
           operation: "forum_preview_msg",
           postback:  "forum_preview_msg",
           param: {
               subject: subject,
               text:    text,
               screen_name: screen_name
           }
       };
    parapara.send_rpc( request );

}


function Para_Forum_Show_Preview( html ) {
    if(this.mode != 'EDITOR')
        return;

    var preview_div     = $('para_forum_msg_preview');
    var preview_console = $('para_forum_msg_preview_console');

    if(!(preview_div && preview_console) )
        return;

    if(html != null)
        preview_console.set( 'html', html );

    preview_div.removeClass('para_hidden');
    preview_div.addClass('para_shown');
}


function Para_Forum_Hide_Preview( html ) {
    if(this.mode != 'EDITOR')
        return;

    var preview_div     = $('para_forum_msg_preview');
    var preview_console = $('para_forum_msg_preview_console');

    if(!(preview_div && preview_console) )
        return;

    if(html != null)
        preview_console.set( 'html', html );
    preview_div.removeClass('para_hidden');
    preview_div.addClass('para_shown');
}



// -- User Events --------------------------------------------------------

function Para_Forum_UEV_ViewIndex() {
    this.load_index();
}


function Para_Forum_UEV_ViewThread( thread_id ) {
    this.load_thread( thread_id );
}


function Para_Forum_UEV_ToggleBody( msg_id ) {
    var mb = this._find_body( msg_id );
    if(mb == null) {
        var request =
            {
                operation: "forum_get_body",
                postback:  "forum_get_body",
                param: {
                    message_id: msg_id
                }
            };
        parapara.send_rpc( request );
    }

    else {
        if( mb.expanded )
            this.hide_body( msg_id );
        else
            this.expand_body( null, msg_id )
    }
}


function Para_Forum_UEV_CreateThread() {
    this.mode           = 'EDITOR';
    this.editor_submode = 'CREATE';

    if(this.form_html == null) {
        this.load_form();
        return;
    }

    this.show_form();
}


function Para_Forum_UEV_ReplyToMsg( msg_id ) {
    this.mode           = 'EDITOR';
    this.editor_submode = 'REPLY';
    this.reply_msg_id   = msg_id;

    if(this.form_html == null) {
        this.load_form();
        return;
    }

    this.show_form();
}


function Para_Forum_UEV_SendMsg() {

    var form = $('para_forum_msgform');
    if(!form)
        return;

    var subj_field = $('para_forum_input_subject');
    var subject = subj_field.get('value').trim();
    form.subject.value = subject;

    var screen_name  = null;

    var text_field = $('para_forum_input_teditor');
    var text    = text_field.get('value').trim();
    form.text.value = text;

    if( this.editor_submode == 'CREATE' ) {
        this.post_new_thread( subject, text, screen_name );
    }
    else if( this.editor_submode == 'REPLY' ) {
        this.reply_to_msg( subject, text, screen_name, this.reply_msg_id );
    }
}


function Para_Forum_UEV_PreviewMessage() {
    if(this.mode != 'EDITOR')
        return;
    var form = $('para_forum_msgform');
    if(!form)
        return;

    var subj_field = $('para_forum_input_subject');
    var subject = subj_field.get('value').trim();
    form.subject.value = subject;

    var screen_name  = null;

    var text_field = $('para_forum_input_teditor');
    var text    = text_field.get('value').trim();
    form.text.value = text;

    this.send_preview_req( subject, text, screen_name );
    this.show_preview('...loading preview...');
}


function Para_Forum_UEV_TFormat( action ) {
    if(this.mode != 'EDITOR')
        return;

    switch(action) {
    case 'bold':
        this.teditor.insert_tags('**', '**', 'Bold'); break;
    case 'italic': 
        this.teditor.insert_tags('//', '//', 'Italic'); break;
    case 'underline':
        this.teditor.insert_tags('__', '__', 'Underline'); break;
    case 'strike':
        this.teditor.insert_tags('--', '--', 'Striked Text'); break;
    case 'ol':
        this.teditor.insert_at_carret("\n  # "); break;
    case 'ul':
        this.teditor.insert_at_carret("\n  * "); break;
    case 'h1':
        this.teditor.insert_tags('==', '==', 'Big Heading'); break;
    case 'h2':
        this.teditor.insert_tags('=', '=', 'Small Heading'); break;
    default:
        break;
    }
}


// Server events ////////////////////////////////////////
function Para_Forum_SEV_GetIndex( response ) {
    var status = response.status;
    if(status == "ok") {
        var html         = response.retval.html;

        this.show_index( html );
    }
    else {
        alert("Para_Forum_SEV_GetThread failed: " + response.error_id );
    }
}



function Para_Forum_SEV_GetThread( response ) {
    var status = response.status;
    if(status == "ok") {
        var html         = response.retval.html;
        var thread_id    = response.retval.thread_id;

        this.show_thread( html, thread_id );
    }
    else {
        alert("Para_Forum_SEV_GetThread failed: " + response.error_id );
    }
}


function Para_Forum_SEV_GetBody( response ) {
    var status = response.status;
    if(status == "ok") {
        var html      = response.retval.html;
        var msg_id    = response.retval.msg_id;

        this.expand_body( html, msg_id );
    }
    else {
        alert("Para_Forum_SEV_GetBody failed: " + response.error_id );
    }    
}


function Para_Forum_SEV_FormLoad( response ) {
   var status = response.status;
   if(status == "ok") {
        var html      = response.retval.html;
        this.form_html = html;

        this.console.empty();
        if(this.editor_submode == 'REPLY') {
            this.show_form();
        }
        if(this.editor_submode == 'CREATE') {
            this.show_form();
        }
    }
    else {
        alert("Para_Forum_SEV_FormLoad failed: " + response.error_id );
    }    

}


function Para_Forum_SEV_CreateThread( response ) {
   var status = response.status;
   if(status == "ok") {
       this.load_index();
   }
   else {
       alert("Para_Forum_SEV_CreateThread failed: " + response.error_id );
   }  

}

function Para_Forum_SEV_PostReply( response ) {
  var status = response.status;
   if(status == "ok") {
       var thread_id = response.retval.thread_id;
       this.load_thread( thread_id );
   }
   else {
       alert("Para_Forum_SEV_PostReply failed: " + response.error_id );
   }
}


function Para_Forum_SEV_PreviewMsg( response ) {
  var status = response.status;
   if(status == "ok") {
        var html      = response.retval.html;
       this.show_preview( html );
   }
   else {
       parapara.status_error("Para_Forum_SEV_PreviewMsg failed: " + response.error_id );
   }

}


// Internal Methods -----------------------------------------------------
function Para_Forum__Add_MsgBody( msg_id, html, expanded ) {
    var ix = this._find_body_index( msg_id );

    var mb = new Para_Forum_MsgBody( msg_id, html, expanded );
    if( ix < 0 )
        this.bodies.push( mb );
    else
        this.bodies[ix] = mb;
}


function Para_Forum__Find_Body_Index( msg_id ) {
    for(var i = 0; i < this.bodies.length; i++) {
        if(this.bodies[i].id == msg_id )
            return i;
    }

    return -1;
}


function Para_Forum__Find_Body( msg_id ) {
    for(var i = 0; i < this.bodies.length; i++) {
        if(this.bodies[i].id == msg_id )
            return this.bodies[i];
    }

    return null;
}



//------ EVENT HANDLERS --------------------------------------------------

function para_forum_uev_view_thread( thread_id ) {
    parapara.forum.uev_view_thread( thread_id );
}

function para_forum_uev_toggle_body( msg_id ) {
    parapara.forum.uev_toggle_body( msg_id );
}

function para_forum_uev_reply_to( msg_id ) {
    parapara.forum.uev_reply_to_msg( msg_id );
}

function para_forum_uev_view_ix(  ) {
    parapara.forum.uev_view_index( );    
}

function para_forum_uev_create_thread() {
    parapara.forum.uev_create_thread();
}


function para_forum_uev_send_msg( ) {
    parapara.forum.uev_send_msg();
    return false;
}


function para_forum_uev_preview( ) {
    parapara.forum.uev_preview_msg();
    return false;
}


function para_forum_uev_tformat( action ) {
    parapara.forum.uev_tformat( action );
    return false;
}

